package com.dm0858.bianmin.wxapi;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;

import androidx.annotation.Nullable;

import com.dm0858.bianmin.R;
import com.dm0858.bianmin.mine.tools.ToastUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
	private static final int RETURN_MSG_TYPE_LOGIN = 1;
	private static final int RETURN_MSG_TYPE_SHARE = 2;
	private IWXAPI api;
	private String strcode;
	private String access_token;
	private String openid;
	public static final String action = "wxentry.broadcast.action";

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID,false);
		if (api == null) {
			api = WXAPIFactory.createWXAPI(this,Constants.APP_ID,false);
			api.registerApp(Constants.APP_ID);
		}
		//如果没回调onResp，八成是这句没有写
		boolean handlerIntent = api.handleIntent(getIntent(), this);
		if (!handlerIntent) {
			ToastUtils.showShort("参数不合法");
			finish();
		}
		StrictMode.setThreadPolicy(new
				StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
		StrictMode.setVmPolicy(
				new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
	}

	// 微信发送请求到第三方应用时，会回调到该方法
	@Override
	public void onReq(BaseReq req) {
	}

	public  String streamGetStr(InputStream is) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			baos.close();
			is.close();
			byte[] byteArray = baos.toByteArray();
			return new String(byteArray);
		} catch (Exception e) {
			//Log.e(tag, e.toString());
			return null;
		}

	}




	// 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
	//app发送消息给微信，处理返回消息的回调
	@Override
	public void onResp(BaseResp resp) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		//LogUtils.sf(resp.errStr);
		//LogUtils.sf("错误码 : " + resp.errCode + "");
		switch (resp.errCode) {

			case BaseResp.ErrCode.ERR_AUTH_DENIED:
			case BaseResp.ErrCode.ERR_USER_CANCEL:
				if (RETURN_MSG_TYPE_SHARE == resp.getType())
				{

					builder.setTitle(R.string.app_tip);
					builder.setMessage(getString(R.string.pay_result_callback_msg, "分享失败！"));
				}
				else
				{
					builder.setTitle(R.string.app_tip);
					builder.setMessage(getString(R.string.pay_result_callback_msg, "登录失败！"));
				}
				break;
			case BaseResp.ErrCode.ERR_OK:
				switch (resp.getType()) {
					case RETURN_MSG_TYPE_LOGIN:
						//拿到了微信返回的code,立马再去请求access_token
						String code = ((SendAuth.Resp) resp).code;
						//LogUtils.sf("code = " + code);
						strcode = code;
						//String value = URLEncoder.encode(String value,"UTF-8");
						handler.sendEmptyMessage(0);
						//String value = urlGet(aaurl);
						break;

					case RETURN_MSG_TYPE_SHARE:
					{
						builder.setTitle(R.string.app_tip);
						builder.setMessage(getString(R.string.pay_result_callback_msg, "分享成功！"));
						finish();
						break;
					}

				}
				break;
		}
	}

	private MyHandler handler = new MyHandler();

	class MyHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case 0:
					getAccessToken();
					break;
				case 1:
					getUserInfo();
					break;
			}
		}
	}

	private void getAccessToken(){
		try {
			String aaurl ="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Constants.APP_ID+"&secret="+Constants.APP_SECRET+"&code="+strcode+"&grant_type=authorization_code";

			byte[] buf = Util.httpGet(aaurl);
			if (buf != null && buf.length > 0) {
				String content = new String(buf);

				JSONObject json = new JSONObject(content);
				access_token=json.getString("access_token");
				openid=json.getString("openid");

				handler.sendEmptyMessage(1);

				Log.e("get server pay params:", content);
			} else {
				Log.d("PAY_GET", "服务器请求错误");
				// Toast.makeText(PayActivity.this, "服务器请求错误", Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	private void getUserInfo() {
		try {
			String aaurl ="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"";

			byte[] buf = Util.httpGet(aaurl);
			if (buf != null && buf.length > 0) {
				String content = new String(buf);

				JSONObject json = new JSONObject(content);
				String headimgurl = json.getString("headimgurl");
				String nickname = json.getString("nickname");
				String unionid = json.getString("unionid");
				Intent intent = new Intent(action);
				Bundle bundle = new Bundle();
				bundle.putString("headimgurl", headimgurl);
				bundle.putString("nickname", nickname);
				bundle.putString("openid", openid);
				bundle.putString("unionid",unionid);
				intent.putExtras(bundle);
				sendBroadcast(intent);
				WXEntryActivity.this.finish();
				Log.e("get server pay params:", content);
			} else {
				Log.d("PAY_GET", "服务器请求错误");
				// Toast.makeText(PayActivity.this, "服务器请求错误", Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
	}
}